<template>
  <div class="page-common-layout">
    <div class="page-common-content">
      <tool-bar
        @search="$refs.table.refresh(true)"
        @reset="
          () => {
            (this.queryParam = {}), $refs.table.refresh(true);
          }
        "
      >
        <template slot="toolBtn" slot-scope="scope">
          <a-button
            class="cu-btn-primary"
            icon="plus"
            @click="add()"
            v-action:processDesign_add
          >
            {{ $ct("NewProcess", "新建流程") }}
          </a-button>
          <!-- v-action:apiFlowableModelAddDialog -->
        </template>
        <template slot="toolForm">
          <a-form-item
            :label="$ct('workflowWorkflowCategoryIndex', '流程分类')"
          >
            <a-select
              show-search
              option-filter-prop="children"
              :filter-option="filterOption"
              v-model="queryParam.modelType"
              :placeholder="$ct('workflowWorkflowCategoryIndex', '流程分类')"
              style="width: 180px;"
            >
              <a-select-option
                v-for="(item, index) in categoryList"
                :key="index"
                :value="item.categoryCode"
              >
                {{ item.categoryName }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item :label="$ct('workflowName', '流程名称')">
            <a-input
              v-model="queryParam.modelName"
              :placeholder="$ct('workflowName', '流程名称')"
              style="width: 100%"
            />
          </a-form-item>
        </template>
      </tool-bar>
      <DataGrid
        ref="table"
        size="small"
        :columns="columns"
        :url="url"
        rowKey="id"
        showPagination="auto"
        :queryParam="queryParam"
        :showRowSelect="false"
      >
        <span slot="processModelType" slot-scope="{ text }">
          {{ text | processModelTypeFilter }}
        </span>
        <span slot="renderModelVersion" slot-scope="{ text, record, index }">
          <a-tag v-if="text" :color="'geekblue'">
            {{ "V:" + record.modelVersion }}
          </a-tag>
        </span>
        <span slot="renderModelType" slot-scope="{ text, record, index }">
          {{ categoryFilters(text) }}
        </span>
        <span slot="renderBirthday" slot-scope="{ text, record, index }">
          <a-tag v-if="record.modelVersion == null" :color="'red'">
            {{ "未发布" }}
          </a-tag>
          <a-tag v-if="record.modelVersion != null" :color="'green'">
            {{ "已发布" }}
          </a-tag>
        </span>
        <span slot="renderAction" slot-scope="{ text, record }">
          <template>
            <a @click="handleEdit(record)">{{ $ct("design", "设计") }}</a>
            <span class="action-margin"></span>
            <a
              @click="handleDel(record)"
              class="action-delete"
              v-action:processDesign_delete
            >
              {{ $ct("delete", "删除") }}
            </a>
            <span class="action-margin"></span>
            <a-dropdown>
              <a class="ant-dropdown-link">
                {{ $ct("more", "更多") }}
                <a-icon type="down" />
              </a>
              <a-menu slot="overlay">
                <a-menu-item>
                  <a @click="release(record)">{{
                    $ct("workFlowRelease", "发布")
                  }}</a>
                </a-menu-item>
                <a-menu-item>
                  <a @click="versionManage(record)">{{
                    $ct("versionManagement", "版本管理")
                  }}</a>
                </a-menu-item>
                <a-menu-item>
                  <a @click="downloadBpmnXml(record)">导出</a>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </template>
        </span>
      </DataGrid>
      <!-- 编辑 -->
      <edit-form
        ref="createModal"
        :visible="visiblerelease"
        :loading="confirmLoading"
        :model="mdlrelease"
        @cancel="releaseHandleCancel(0)"
        @ok="releaseHandleOk"
      />
      <!-- 版本控制 -->
      <versionForm
        ref="versionForm"
        :visible="visibleVersion"
        :loading="confirmLoadingVersion"
        :model="mdlVersion"
        @cancel="handleCancelVersion()"
        @ok="handleOkVersion"
        @refresh="refreshTable"
      ></versionForm>
      <!-- 流程设计 -->
      <flowDesign
        ref="designModal"
        :isEdit="isEdit"
        :visible="visibleDesign"
        :loading="confirmLoadingDesign"
        @cancel="handleCancel"
        @ok="handleOkFlowDesign"
      ></flowDesign>

      <add-form
        ref="subModal"
        :visible="addVisible"
        @click="openPage"
        @cancel="() => (addVisible = false)"
      />
      <!-- 系统表单 -->
      <system-form
        ref="systemFormModal"
        :visible="systemFormsVisible"
        @cancel="systemFormHandleCancel"
        @ok="systemFormHandleOk"
      />
      <!-- 自定义表单 -->
      <customer-form
        ref="customerFormModal"
        :visible="customerFormVisible"
        @cancel="systemFormHandleCancel()"
        @ok="customerFormOk"
      />
    </div>
  </div>
</template>

<script>
import flowDesign from "./dataModel";
import editForm from "./edit";
import addForm from "./add";
import systemForm from "./systemForm";
import customerForm from "./customerForm";
import versionForm from "./version";
import { dataGridMixin } from "@/mixins/dataGridMixin";
import { DataGrid } from "@/components";
import { ACCESS_TOKEN } from "@/store/mutation-types";
import Vue from "vue";
import { baseUrl } from "@/services/baseUrl";

export default {
  name: "TableList",
  mixins: [dataGridMixin],
  components: {
    DataGrid,
    editForm,
    versionForm,
    flowDesign,
    customerForm,
    addForm,
    systemForm,
  },
  data() {
    return {
      columns: [
        {
          title: "流程名称",
          dataIndex: "modelName",
          langCode: "workflowName",
          width: 150,
        },
        {
          title: "流程标识",
          dataIndex: "modelKey",
          langCode: "workflowId",
          width: 150,
        },
        {
          title: "流程分类",
          dataIndex: "modelType",
          align: "center",
          langCode: "workflowClassification",
          scopedSlots: {
            customRender: "renderModelType",
          },
          width: 80,
        },
        {
          title: "流程类型",
          dataIndex: "processModelType",
          align: "center",
          langCode: "workflowType",
          width: 80,
          scopedSlots: { customRender: "processModelType" },
        },
        {
          title: "流程版本",
          width: 80,
          dataIndex: "modelVersion",
          align: "center",
          langCode: "workflowVersion",
          scopedSlots: { customRender: "renderModelVersion" },
        },
        {
          title: "发布状态",
          dataIndex: "birthday",
          scopedSlots: { customRender: "renderBirthday" },
          align: "center",
          langCode: "publishingStatus",
          width: 100,
        },
        {
          title: "操作",
          width: 180,
          dataIndex: "action",
          scopedSlots: { customRender: "renderAction" },
          align: "center",
        },
      ],
      visible: false,
      visiblerelease: false,
      confirmLoading: false,
      mdl: null,
      mdlrelease: null,
      advanced: true,
      queryParam: {},
      url: {
        getPageSet: "/workflow/apiFlowableModel/getPageSet",
        deleteBatch: "/workflow/apiFlowableModel/deleteModel",
        downLoadXmlByModelId: "/workflow/apiFlowableModel/downLoadXmlByModelId",
        deployModelId: "/workflow/apiFlowableModel/deployModelId",
      },
      mdlVersion: null,
      confirmLoadingVersion: false,
      visibleVersion: false,
      visibleDesign: false,
      confirmLoadingDesign: false,
      spinLoading: false,
      isEdit: false,
      categoryList: [],
      addVisible: false,
      //打开表单中心界面
      systemFormsVisible: false,
      //打开手写的界面
      customerFormVisible: false,
      formUuid: "",
      modelType: null, // 1自己写的表单  2拖动设计的
    };
  },
  created() {
    this.getCategory();
  },
  mounted() {},
  filters: {
    processModelTypeFilter(processModelType) {
      const sexMap = {
        2: "自定义表单",
        1: "系统表单",
      };
      return sexMap[processModelType];
    },
  },
  methods: {
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    systemFormHandleCancel() {
      this.systemFormsVisible = false;
      this.customerFormVisible = false;
    },
    systemFormHandleOk(uuid) {
      // 设计
      this.formUuid = uuid;
      this.modelType = 1;
      // this.$refs.designModal.getData(e);
      this.addVisible = false;
      this.visibleDesign = true;
      this.systemFormsVisible = false;
      this.isEdit = false;
    },
    customerFormOk(uuid) {
      // 设计
      this.formUuid = uuid;
      this.modelType = 2;
      // this.$refs.designModal.getData(e);
      this.addVisible = false;
      this.visibleDesign = true;
      this.customerFormVisible = false;
      this.isEdit = false;
      // this.getFormDesign();
    },
    // 打开设计页面
    openPage(key) {
      //关联表中新的表单
      if ("systemForms" == key) {
        this.systemFormsVisible = true;
        return;
      }
      if ("customerForm" == key) {
        this.customerFormVisible = true;
      }
      if ("createTemplate" == key) {
        return alert("敬请期待");
      }
    },
    //打开新增界面
    add() {
      // this.addVisible = true

      this.visibleDesign = true;
      this.isEdit = false;
    },
    categoryFilters(val) {
      const category = this.categoryList.filter((res) => {
        return res.categoryCode === val;
      });
      if (category.length > 0) {
        return category[0].categoryName;
      } else {
        return "";
      }
    },
    getCategory() {
      this.$post("/workflow/flowCategory/getAllData").then((res) => {
        this.categoryList = res;
      });
    },
    //新建流程界面
    handleAddFlow() {
      this.visibleDesign = true;
      this.isEdit = false;
      this.$refs.designModal.setFlowXml();
    },
    // 发布
    release(record) {
      this.mdlrelease = {
        modelId: record.id,
        procdefId: record.procdefId,
      };
      this.visiblerelease = true;
      this.$refs.createModal.getList();
    },
    // 编辑
    handleEdit(record) {
      let that = this;
      that.spinLoading = true;
      that.mdl = { ...record };
      that.isEdit = true;
      // 获取表单流程详情
      that
        .$post("/workflow/flowModel/getDetailByModelKey", {
          modelKey: that.mdl.modelKey,
          procdefId: that.mdl.procdefId,
          type: "mode",
        })
        .then((res) => {
          if (res.statusCode !== 300) {
            that.formUuid = res.flowModel.formUuid;
            that.modelType = res.flowModel.modelType;
            that.visibleDesign = true;
            that.confirmLoadingDesign = true;
            setTimeout(function() {
              that.$refs.designModal.setAllData(res);
            }, 300);
            // that.getFormDesign();
          } else {
            that.visibleDesign = false;
            that.$message.error(res.message);
          }
        })
        .finally(() => {
          that.spinLoading = false;
          that.confirmLoading = false;
          that.confirmLoadingDesign = false;
        });
      // this.$refs.designForm.setAllData(this.mdl.modelKey,this.mdl.procdefId)
    },
    handleCancel(e) {
      let that = this;
      that.$confirm({
        title: "警告",
        content: "关闭后所有未保存的数据将会清空，是否确定关闭！",
        okText: "确定",
        cancelText: "取消",
        closable: true,
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          that.addVisible = false;
          that.visibleDesign = false;
          that.systemFormsVisible = false;
          that.customerFormVisible = false;
        },
      });
    },
    // 取消发布
    releaseHandleCancel() {
      this.visiblerelease = false;
    },
    // 版本控制
    versionManage(e) {
      this.visibleVersion = true;
      this.mdlVersion = e.modelKey;
      if (this.$refs.versionForm)
        this.$refs.versionForm.refreshList(e.modelKey);
    },
    handleCancelVersion() {
      this.visibleVersion = false;
    },
    handleOkVersion() {
      this.visibleVersion = false;
      this.$refs.table.refresh();
    },
    // 删除
    handleDel(record) {
      const that = this;
      if (record.modelVersion != null) {
        return this.$message.error(
          "该流程已经发布部署，请去部署流程界面删除！！！"
        );
      }
      that.$confirm({
        title: "警告",
        content: `此操作将永久删除该数据，确定要执行该操作吗?`,
        okText: "确定",
        cancelText: "取消",
        closable: true,
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          // 在这里调用删除接口
          that
            .$post(that.url.deleteBatch, {
              modelId: record.id,
              procdefId: record.procdefId,
            })
            .then((res) => {
              if (res.statusCode === 200) {
                that.$message.success(res.message);
                that.$refs.table.refresh();
              } else {
                that.$message.error(res.message);
              }
            });
          return new Promise((resolve, reject) => {
            setTimeout(Math.random() > 0.5 ? resolve : reject, 1000);
          }).catch(() => console.log("Oops errors!"));
        },
        onCancel() {
          console.log("Cancel");
        },
      });
    },
    // 下载
    downloadBpmnXml(record) {
      window.location.href =
        baseUrl +
        "/workflow/apiFlowableModel/downLoadXmlByModelId?modelId=" +
        record.id +
        "&token=" +
        Vue.ls.get(ACCESS_TOKEN);
    },
    // 确定发布
    releaseHandleOk() {
      const form = this.$refs.createModal.form;
      this.confirmLoading = true;
      form.validateFields((errors, values) => {
        if (!errors) {
          this.$post(this.url.deployModelId, values).then((res) => {
            if (res.statusCode === 200) {
              this.visiblerelease = false;
              this.confirmLoading = false;
              form.resetFields();
              this.$refs.table.refresh();
              this.$message.success(res.message);
            } else {
              this.confirmLoading = false;
              this.$message.error(res.message);
            }
          });
        } else {
          this.confirmLoading = false;
        }
      });
    },
    refreshTable() {
      this.visibleVersion = false;
      this.$refs.table.refresh();
    },
    // 流程设计提交
    handleOkFlowDesign(bpmData, uuid) {
      const that = this;
      // if (
      //     bpmData.formBtnList.length === 0 ||
      //     (bpmData.formBtnList && !bpmData.formBtnList[0].nodeButtonCode)
      // ) {
      //   that.$message.warn("请先配置节点按钮！");
      //   return true;
      // }

      if (!that.isEdit) {
        that.$confirm({
          title: "提示",
          content: "请修改流程标识和流程名称,便于进行业务处理",
          okText: "已修改,提交",
          cancelText: "去修改",
          onOk() {
            that.handleSubmitXML(bpmData, uuid);
          },
          onCancel() {},
        });
      } else {
        that.handleSubmitXML(bpmData, uuid);
      }
    },
    handleSubmitXML(bpmData, uuid) {
      let url = "";
      this.confirmLoadingDesign = true;
      let parameter = {
        modelType: this.modelType,
        uuid: uuid,
        actFormConfigureUuid: this.formUuid,
        formBtnList: JSON.stringify(bpmData.formBtnList),
        formFieldList: JSON.stringify(bpmData.formFieldList),
        // formModel: formData.formModel,
        formFieldList: JSON.stringify(bpmData.formFieldList),
        formNoticeList: JSON.stringify(bpmData.formNoticeList),
        actMyNodeFormFieldList: JSON.stringify(bpmData.actMyNodeFormFieldList),
        actMyNodeFormList: JSON.stringify(bpmData.actMyNodeFormList),
        permissionType: bpmData.permissionType,
        permissionValue: bpmData.permissionValue,
        processModelType: this.modelType, //区分自定义 和可视化
        batchApproval: bpmData.batchApproval, // 是否开启批量审批
        // ifMultiForm: bpmData.ifMultiForm, // 是否开启多表单
        ifMultiForm: "1", // 默认开启多表单
        sign: bpmData.sign,
      };
      if (!uuid) {
        parameter.modelName = bpmData.processName;
        parameter.flowJson = bpmData.xml;
        parameter.modelKey = bpmData.processKey; //efd_ht_task
        parameter.modelId = bpmData.processId;
        url = "/workflow/flowModel/save";
      } else {
        parameter.actDeModelName = bpmData.processName;
        parameter.flowDesign = bpmData.xml;
        parameter.actDeModelKey = bpmData.processKey;
        parameter.actDeModelId = bpmData.processId;
        parameter.procdefId = this.mdl.procdefId;
        url = "/workflow/flowModel/updateData";
      }
      this.$post(url, parameter).then((res) => {
        if (res.statusCode === 200) {
          this.confirmLoadingDesign = false;
          this.visibleDesign = false;
          this.$message.success(res.message);
          this.$refs.table.refresh();
        } else {
          this.confirmLoadingDesign = false;
          this.$message.error(res.message);
        }
      });
    },
    // 获取表单设计数据
    getFormDesign() {
      this.$post("/form/formBasicConfigure/getDetailByUuid", {
        uuid: this.formUuid,
      }).then((res) => {
        this.$bus.$emit("getFormDesign", res.formDesign.designJson);
        this.$bus.$emit("getUpdateList", []);
      });
    },
  },
};
</script>

<style lang="less" scoped="scoped">
/deep/ .ant-drawer-body {
  padding: 0 !important;
}
</style>
